package cn.lijia.itrip.controller;

import cn.lijia.itrip.common.*;
import cn.lijia.itrip.exception.ItripException;
import cn.lijia.itrip.model.ItripUser;
import cn.lijia.itrip.model.ItripUserVo;
import cn.lijia.itrip.service.ItripUserService;
import cn.lijia.itrip.vo.LoginResultVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;

import static sun.net.www.protocol.http.HttpURLConnection.userAgent;

/**
 * @author 李嘉
 * @create 2018-08-28-12:00
 */
@Controller
@RequestMapping("/api")
public class ItripUserController {

    @Resource
    private ItripUserService itripUserService;

    @Resource
    private ValidationUtil validationUtil;

    @Resource
    private RedisAPI redisAPI;


    @RequestMapping("/user/getById/{userId}")
    @ResponseBody
    public Dto getById(@PathVariable("userId") Long userId, HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            ItripUser user = itripUserService.getById(12l);
            if (user == null) {
                return DtoUtil.returnFail("Token已失效", ErrorCode.AUTH_TOKEN_INVALID);
            }
            ItripUser itripUser = itripUserService.getById(userId);
            return DtoUtil.returnDataSuccess(user);

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("查询异常","1001");
        }
    }

    //验证用户名是否存在
    @RequestMapping(value = "/ckusr",method = RequestMethod.GET)
    @ResponseBody
    public Dto validateItripUserName(HttpServletRequest request) {
        String name = request.getParameter("name");
        ItripUser itripUser = null;
        try {
            itripUser = itripUserService.findByUserCode(name);
            //用户名存在
            if(itripUser != null){
                return DtoUtil.returnFail("用户名已经存在",ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }
            //用户不存在
            return DtoUtil.returnSuccess("用户名可用");
        } catch (ItripException e){
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),e.getErrorCode());
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("注册失败",ErrorCode.AUTH_REGIST_FAILURE);
        }
    }

    /**
     * 手机短信验证
     */
    @ResponseBody
    @RequestMapping(value = "/validatephone", method = RequestMethod.PUT)
    public Dto ValidatePhone(String user,String code){
        //缓存中有此用户注册时发送验证码的key
        if(redisAPI.exists("valCode"+user)) {
            //获取这个用户注册时发送code剩余过期时间
            Long ttl = redisAPI.ttl("valCode" + user);
            //获取缓存中的值
            String valCode = redisAPI.get("valCode" + user);
            //缓存的验证码相同并且验证时间大于0，才可以激活成功
            if (valCode.equals(code) && ttl > 0) {
                //删除缓存中的验证码
                redisAPI.del("valCode"+user);
                try {
                    //从数据库中查询对应的用户
                    ItripUser itripUser = itripUserService.findByUserCode(user);
                    System.out.println(itripUser);
                    if(itripUser == null){
                       return DtoUtil.returnFail("用户不存在",ErrorCode.AUTH_UNKNOWN);
                    }
                    //此时激活成功，修改用户的激活状态
                    itripUser.setActivated(1);
                    itripUserService.modify(itripUser);
                } catch (Exception e) {
                    e.printStackTrace();
                    return DtoUtil.returnFail("手机注册短信激活失败1",ErrorCode.AUTH_PHONE_ACTIVATE_FAILURE);
                }
                return DtoUtil.returnSuccess("手机注册短信激活成功");
            }
        }
        return DtoUtil.returnFail("手机注册短信激活失败2",ErrorCode.AUTH_PHONE_ACTIVATE_FAILURE);
    }


    /**
     * 手机注册账号
     * @param userVo 前台返回的用户信息（JSON格式）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/registerbyphone",method = RequestMethod.POST)
    public Dto RegisterByPhone(@RequestBody ItripUserVo userVo){
        try {
            HashMap hashMap = itripUserService.SDKSendTemplateSMS(userVo.getUserCode());
            //获取手机发送短信中的验证码
            Integer valCode = (Integer) hashMap.get("valCode");
            //注意上面需要先强转为Integer,不能直接强制为String,否则报类型转换异常
            String code = String.valueOf(valCode);
            //将验证码保存到缓存中，这里需要加上用户的userCode,这样就可以保证缓存中存储的唯一性
            redisAPI.set("valCode"+userVo.getUserCode(),code,1000 * 4);
            //保存用户,但是未激活
            ItripUser itripUser = new ItripUser();
            itripUser.setUserCode(userVo.getUserCode());
            itripUser.setUserName(userVo.getUserName());
            //密码加密
            String userPassword = DigestUtil.hmacSign(userVo.getUserPassword());
            itripUser.setUserPassword(userPassword);
            itripUserService.save(itripUser);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("注册失败",ErrorCode.AUTH_REGIST_FAILURE);
        }
        return DtoUtil.returnSuccess("注册成功但是未激活");
    }


}
